<?php
C('build/making');
// 物品参数ID关联
$mat_type_list = array(
	'cook', //食品
	'drink', //饮料
	'furniture', //家具
//	'finery', //服饰
);
$recipe_num = 5;
$recipe_sql_tpl = file_get_contents($G['path_cfg'].'making/recipe_tpl.sql');
foreach ($mat_type_list as $name) {
	
	$sql = sprintf($recipe_sql_tpl, $name, $name);
	$ret = $DB->exeSql($sql);
	
	// 获取配方材料,工艺等名称
	$file = $_dir.'chdocs/making-param-txt/'.$name.'.txt';
	
	if (!is_file($file)) {
		echo $file.' is not exists!';
		exit;
	}
	
	$text = file_get_contents($file);
	
	$text = iconv('gb2312', 'utf-8', $text);
	$arr = explode("\r\n", $text);
	array_unshift($arr, '');
	unset($arr[0]);
	foreach ($arr as $k=>$v) {
		if (empty($v)) {
			unset($arr[$k]);
		}
	}
	
	for ($i=1; $i<= $recipe_num; $i++) {
		// 
		$file = $_dir.'chdocs/making-param-txt/'.$name.sprintf('%02d', $i).'.txt';
		
		if (!is_file($file)) {
			echo $file.' is not exists!';
			exit;
		}
		
		$text = file_get_contents($file);
		
		$data = array('');
		$_arr = explode("\r\n", $text);
		foreach ($_arr as $v) {
			if (empty($v)) continue;
			$tmp = explode(',', $v);
			array_unshift($tmp, '');
			unset($tmp[0]);
			$data[] = $tmp;
		}
		unset($data[0]);
		saveRecipe($data, $name, $i);
	}
	
	
	$str  = '$GLOBALS[\'G\'][\''.$name.'_sec_mat_item\'] = '
			.var_export($GLOBALS['G'][$name.'_sec_mat_item'], true).";\n";
	$str .= '$GLOBALS[\'G\'][\''.$name.'_param_list\'] = '.var_export($arr, true).";\n";
//	$str .= 'return '.var_export($data, true);
	
	
	$filename = $_dir.'inc/conf/making/'.$name.'_param.cfg.php';
	writefile($filename, $str, 'php');
}

/**
 * 保存配方
 * @param array $data 配方数据
 * @param string $making_name 制造类型名称
 * @param array $recipe_no 配方编号
 */
function saveRecipe($data, $making_name, $recipe_no)
{
	global $DB;
	
	
	$sqlValue = array();
	foreach ($data as $x => $xv) {
		foreach ($xv as $y=>$yv) {
			$x_y = $x.'-'.$y;
			$y_x = $y.'-'.$x;
			if (isset($sqlValue[$y_x])) continue;
			if ($x == $y) $yv = 1000;
			$sqlValue[$x_y] = '('.$recipe_no.', \''.$x_y.'\', \''.$y_x.'\', '.$yv.')';
		}
	}
	$sqlValue = join(",\n", $sqlValue);
	$sql = 'INSERT INTO tpl_recipe_'.$making_name.' (`recipe_no`, `x_y`, `y_x`, `val`) VALUES '.$sqlValue;
	$ret = $DB->exeSql($sql);
	
	if (!$ret) {
		var_export($DB->errors);
		exit;
	}
}












